package com.cddata;

import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;

import javax.swing.JOptionPane;

import org.hibernate.Session;

import com.cddata.util.DBOperation;
import com.cddata.util.HibernateUtil;


public class FileDataThread extends  Thread { 
	public FileDataThread() {

	}
	
	public FileDataThread( File aFile, String aFileName ) {
		this.file = aFile;
		this.fileName = aFileName;
	}
	
	public void run() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		BufferedReader bf = null;
		String readLine = null;
		StringTokenizer sToken = null;
		String path = null;
		String size = null;
		int lineCount = 0;
		boolean goodToGo = true;
		try{
			bf = new BufferedReader(new FileReader(file));
			while( ( readLine = bf.readLine() ) != null) {
				lineCount++;
			}
			DBOperation.getHelperBean().setLines(lineCount);
			DBOperation.getHelperBean().setProcessFinished(false);
			DBOperation.getHelperBean().setFileName(fileName);
			t2 = new FileDataProgress();
			bf = new BufferedReader(new FileReader(file));
			
			while( ( readLine = bf.readLine() ) != null) {
				sToken = new StringTokenizer( readLine, "\t");
				while( sToken.hasMoreElements() ) {
					path = sToken.nextToken();
					size = sToken.nextToken();
					DBOperation.getHelperBean().setLabelText(path);
					session = DBOperation.createAndInsertContent( session, fileName, path, size );
					++insertedcount;
				}
				DBOperation.getHelperBean().setInsertedLines(insertedcount);
				if( insertedcount == lineCount ) {
					DBOperation.getHelperBean().setProcessFinished(true);
				}
				EventQueue.invokeLater(t2);				
			}
		}catch (Exception e) {
			e.printStackTrace();
			goodToGo = false;
			JOptionPane.showMessageDialog(null, e.getStackTrace());
		}
		if( goodToGo ) {
			session.getTransaction().commit();
			JOptionPane.showMessageDialog(null, "Uploaded '"+ lineCount +"' rows from file " + fileName);
		}
	}
	
	int insertedcount = 0;
	Runnable t2 = null;
	File file = null;
	String fileName = null;
}
